package org.dreamwork.tools.code.analyzer.core;

import org.dreamwork.misc.MimeType;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileStatistician {
    public static String DEFAULT_IGNORED =
            ".git/;target/;src/main/webapp/;*.iml;.gitignore;*.otf;*.ttf;*.png;*.eot;*.woff2;*.svg;*.xlsx;*.woff";
    private static final int MAX_SIZE = 1 << 20;    // 1M
    private final Path file;

    private int last;
    private long total, cr, lf, crlf;
    private MimeType type;

    public FileStatistician (String fileName) throws FileNotFoundException {
        file = Paths.get (fileName);
        if (!Files.exists (file)) {
            throw new FileNotFoundException (fileName);
        }
    }

    public void statistics () throws IOException {
        total = Files.size (file);
        byte[] buff = new byte[(int) Math.min (total, MAX_SIZE)];
        try (InputStream in = Files.newInputStream (file)) {
            int length, i = 0;
            while ((length = in.read (buff)) != -1) {
                for (i = 0; i < length; i ++) {
                    switch (buff[i]) {
                        case '\r': cr ++; break;
                        case '\n':
                            lf ++;
                            if (last == '\r') crlf ++;
                            break;
                    }
                    last = buff[i];
                }
            }
        }
    }

    public long getCr () {
        return last == '\r' ? cr : cr + 1;
    }

    public long getLf () {
        return last == '\n' ? lf : lf + 1;
    }

    public long getCrlf () {
        return crlf;
    }

    public long getTotal () {
        return total;
    }

    public MimeType getType () {
        return type;
    }
}